<template>
  <div class="main-container">
    <!-- 左侧分类按钮 -->
    <div class="left-buttons">
      <button
        v-for="category in mainCategories"
        :key="category.id"
        class="side-btn"
        :class="{ active: currentCategory === category.id }"
        @click="switchCategory(category)"
      >
        {{ category.display_name }}
        <span v-if="categoryStats[category.id]" class="category-count">({{ categoryStats[category.id] }})</span>
      </button>
    </div>

    <!-- 主要内容区域 -->
    <div class="search-content">
      <div class="search-container">
        <!-- 搜索头部 -->
        <div class="search-header">
          <form class="search-form" @submit.prevent="goToSearchPage">
            <input
              type="text"
              class="search-box"
              v-model="searchKeyword"
              :placeholder="currentPlaceholder"
            >
            <button type="submit" class="search-button">
              <span>搜索</span>
            </button>
          </form>
          <button class="login-btn" @click="goToLogin">
            <img :src="avatarUrl" class="avatar" alt="登录">
          </button>
        </div>

        <!-- 排序和筛选 -->
        <div class="sort-container" v-if="showSort">
          <button 
            v-for="(option, key) in sortOptions" 
            :key="key"
            class="sort-btn"
            :class="{ active: currentSort === key }"
            @click="changeSort(key)"
          >
            {{ option.label }}
          </button>
        </div>

        <!-- 修改二级分类按钮显示 -->
        <div class="category-buttons" v-if="currentSubCategories.length > 0">
          <button
            v-for="subCategory in currentSubCategories"
            :key="subCategory.id"
            class="category-btn"
            :class="{ active: currentSubCategory === subCategory.id }"
            @click="switchSubCategory(subCategory)"
          >
            {{ subCategory.display_name }}
          </button>
        </div>

        <!-- 轮播图 -->
        <div class="carousel-container">
          <div
            v-for="(slide, index) in slides"
            :key="slide.id"
            class="carousel-slide"
            :class="{ active: currentSlideIndex === index }"
          >
            <img :src="slide.image" :alt="slide.alt" @click="viewProduct(slide.id)">
          </div>
        </div>

        <!-- 显示区域标题 -->
        <div v-if="viewMode !== 'search'" class="section-title">
          <h2>{{ sectionTitle }}</h2>
          <button class="section-toggle" @click="toggleViewMode">
            {{ viewMode === 'recommend' ? '查看热门' : '查看推荐' }}
          </button>
        </div>

        <!-- 商品列表 -->
        <div class="product-grid">
          <div
            v-for="product in products"
            :key="product.product_code"
            class="product-card"
          >
            <!-- <div class="product-actions">
              <button 
                class="favorite-btn" 
                :class="{ active: product.isFavorite }"
                @click.stop="toggleFavorite(product)"
              >
                ♥
              </button>
            </div> -->
            <img 
              :src="product.image" 
              class="product-image" 
              :alt="product.title || product.name"
              @click="viewProduct(product)"
            >
            <div class="product-info">
              <div class="product-title">{{ product.title || product.name }}</div>
              <div class="product-price">¥{{ product.price }}</div>
            </div>
          </div>
        </div>
        <div v-if="products.length === 0 && !isLoading" class="no-products">
          <el-empty 
            :description="viewMode === 'search' ? 
              `没有找到与'${searchKeyword}'相关的商品` : 
              '没有找到相关商品'"
            :image-size="200">
            <el-button v-if="viewMode === 'search'" @click="clearSearch">清空搜索</el-button>
          </el-empty>
        </div>
        <div v-show="isLoading" class="loading">加载中...</div>

        <!-- 最近浏览 -->
        <div v-if="recentViews.length > 0" class="recent-views">
          <h3>最近浏览</h3>
          <div class="recent-views-container">
            <div 
              v-for="product in recentViews" 
              :key="product.product_code"
              class="recent-view-item"
              @click="viewProduct(product)"
            >
              <img :src="product.image" :alt="product.title">
              <div class="recent-view-title">{{ product.title }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { 
  sortOptions,
  processProductData,
  loadProducts,
  addToRecentViews
} from '@/utils/productUtils'
import {DEFAULT_AVATAR} from '@/utils/userUtils'
const router = useRouter()

// 用户头像
const avatarUrl = computed(() => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  try {
    const avatar = localStorage.getItem('user_avatar')
    if (avatar && isLoggedIn) {
      return avatar || DEFAULT_AVATAR
    }
  } catch (e) {
    console.error('解析 user_info 失败', e)
  }
  return DEFAULT_AVATAR
})

// 新增变量
const categoryStats = ref({}) // 分类商品数量统计
const viewMode = ref('recommend') // 视图模式：recommend(推荐)、popular(热门)、search(搜索)
const recentViews = ref([]) // 最近浏览

const currentSort = ref('newest')
const showSort = ref(false)
const favoriteProducts = ref({}) // 收藏的商品映射

// 分类数据
const mainCategories = ref([]) // 清空硬编码的分类

// 状态管理
const currentCategory = ref(null)//当前分类
const currentSubCategories = ref([])//当前子分类
const currentSubCategory = ref(null)//当前子分类
const searchKeyword = ref('')//搜索关键词
const currentSlideIndex = ref(0)//当前轮播图索引
const isLoading = ref(false)//加载状态
const page = ref(1)//当前页码
const products = ref([])

// 轮播图数据
const slides = ref([
  { id: 1, image: 'https://picsum.photos/1200/400?random=1', alt: '广告1' },
  { id: 2, image: 'https://picsum.photos/1200/400?random=2', alt: '广告2' },
  { id: 3, image: 'https://picsum.photos/1200/400?random=3', alt: '广告3' }
])

// 计算属性：区域标题
const sectionTitle = computed(() => {
  if (viewMode.value === 'recommend') return '推荐商品'
  if (viewMode.value === 'popular') return '热门商品'
  if (viewMode.value === 'search') return '搜索结果'
  return ''
})

// 切换视图模式
const toggleViewMode = () => {
  viewMode.value = viewMode.value === 'recommend' ? 'popular' : 'recommend'
  products.value = []
  page.value = 1
  loadProducts()
}

// 改变排序方式
const changeSort = async (sortKey) => {
  currentSort.value = sortKey;
  products.value = [];
  page.value = 1;
  
  try {
    let apiUrl = '';
    if (currentSubCategory.value) {
      apiUrl = `/api/products/categories/${currentSubCategory.value}/products/`;
    } else if (currentCategory.value) {
      apiUrl = `/api/products/categories/${currentCategory.value}/products/`;
    } else if (mainCategories.value.length > 0) {
      apiUrl = `/api/products/categories/${mainCategories.value[0].id}/products/`;
    }

    if (apiUrl) {
      products.value = await handleLoadProducts(apiUrl, {
        page: page.value,
        currentSort: currentSort.value,
        searchKeyword: searchKeyword.value,
        favoriteProducts: favoriteProducts.value
      });
    }
  } catch (error) {
    console.error('加载商品失败:', error);
    ElMessage.error('加载商品失败，请稍后重试');
  }
};

// 将原来的静态 categoryConfig 替换为动态生成的版本
const categoryConfig = ref({})

// 修改 fetchCategories 函数，添加对 categoryConfig 的处理
const fetchCategories = async () => {
  try {
    console.log('开始获取分类数据')
    const response = await axios.get('/api/products/categories/')
    
    // 存储到本地
    localStorage.setItem('categories', JSON.stringify({
      data: response.data,
      timestamp: Date.now()
    }))
    
    mainCategories.value = response.data
    
    // 动态生成 categoryConfig
    const config = {}
    response.data.forEach(category => {
      config[category.id] = {
        placeholder: `搜索${category.display_name}...`,
        color: '#45a049'
      }
    })
    categoryConfig.value = config

    // 设置默认选中第一个分类
    if (response.data.length > 0) {
      currentCategory.value = response.data[0].id
      currentSubCategories.value = response.data[0].children || []
    }
    
    // 加载分类统计信息
    fetchCategoryStats()
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 获取分类统计信息 (该接口可能需要后端实现)
const fetchCategoryStats = async () => {
  try {
    // 如果后端没有提供此API，可以在这里模拟或者移除这个功能
    // const response = await axios.get('/api/products/categories/stats/')
    // const stats = {}
    // response.data.forEach(item => {
    //   stats[item.id] = item.product_count
    // })
    // categoryStats.value = stats
    
    // 临时解决方案：不使用统计数据
    categoryStats.value = {}
  } catch (error) {
    console.error('获取分类统计信息失败:', error)
  }
}

// 加载用户的收藏商品
const loadFavorites = async () => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  if (!isLoggedIn) return
  
  try {
    // 如果后端提供了收藏接口，则使用以下代码
    // const response = await axios.get('/api/products/favorites/')
    // const favMap = {}
    // response.data.forEach(product => {
    //   favMap[product.id] = true
    // })
    // favoriteProducts.value = favMap
    
    // 临时解决方案：不使用收藏数据
    favoriteProducts.value = {}
  } catch (error) {
    console.error('加载收藏失败:', error)
  }
}

// 切换收藏状态
const toggleFavorite = async (product) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  if (!isLoggedIn) {
    router.push('/login')
    return
  }
  
  try {
    // 如果后端提供了收藏接口，则使用以下代码
    // if (favoriteProducts.value[product.id]) {
    //   await axios.post(`/api/products/${product.id}/unfavorite/`)
    //   favoriteProducts.value[product.id] = false
    // } else {
    //   await axios.post(`/api/products/${product.id}/favorite/`)
    //   favoriteProducts.value[product.id] = true
    // }
    
    // 临时解决方案：仅在前端切换状态
    favoriteProducts.value[product.product_code] = !favoriteProducts.value[product.product_code]
    
    // 更新产品数据中的收藏状态
    product.isFavorite = favoriteProducts.value[product.product_code] || false
  } catch (error) {
    console.error('切换收藏状态失败:', error)
  }
}

// 从本地缓存加载分类
const loadCategoriesFromCache = () => {
  try {
    const cached = localStorage.getItem('categories')
    if (cached) {
      const { data, timestamp } = JSON.parse(cached)
      // 24小时缓存
      if (Date.now() - timestamp < 24 * 60 * 60 * 1000) {
        
        mainCategories.value = data
        
        const config = {}
        data.forEach(category => {
          config[category.id] = {
            placeholder: `搜索${category.display_name}...`,
            color: '#45a049'
          }
        })
        categoryConfig.value = config
        if (data.length > 0) {
          currentCategory.value = data[0].id
          currentSubCategories.value = data[0].children || []
        }
        return true
      }
    }
    return false
  } catch (error) {
    console.error('读取缓存分类失败:', error)
    return false
  }
}

// 分类切换函数
const switchCategory = async (category) => {

  currentCategory.value = category.id
  currentSubCategories.value = category.children || []
  currentSubCategory.value = null // 重置二级分类选择

  products.value = [] // 清空现有商品
  page.value = 1 // 重置页码
  viewMode.value = 'recommend' // 重置为推荐模式
  showSort.value = false // 隐藏排序选项
  const apiUrl = `/api/products/categories/${currentCategory.value}/products/`;
  try {
    products.value = await handleLoadProducts(apiUrl, {
      page: page.value,
      currentSort: currentSort.value,
      searchKeyword: searchKeyword.value,
      favoriteProducts: favoriteProducts.value
    });
  }catch (error) {
    console.error('加载商品失败:', error);
  }
}

const switchSubCategory =async (subCategory) => {

  currentSubCategory.value = subCategory.id

  products.value = [] // 清空现有商品
  page.value = 1 // 重置页码
  viewMode.value = 'recommend' // 重置为推荐模式
  showSort.value = true // 显示排序选项
  const apiUrl = `/api/products/categories/${currentSubCategory.value}/products/`;
  try {
    products.value = await handleLoadProducts(apiUrl, {
      page: page.value,
      currentSort: currentSort.value,
      searchKeyword: searchKeyword.value,
      favoriteProducts: favoriteProducts.value
    });
  } catch (error) {
    console.error('加载商品失败:', error);
  }
}

// 搜索框placeholder
const currentPlaceholder = computed(() => {
  if (!currentCategory.value || !categoryConfig.value[currentCategory.value]) {
    return '搜索商品...'
  }
  return categoryConfig.value[currentCategory.value].placeholder
})

// 处理搜索
async function handleSearch() {
  if (!searchKeyword.value.trim()) return
  // 切换到搜索模式
  viewMode.value = 'search'
  showSort.value = true
  
  // 重置页码，重新搜索
  page.value = 1
  products.value = [] // 清空现有商品列表
  isLoading.value = true
  
  try {
    // 使用搜索API
    const searchUrl = `/api/products/buyer/search?q=${encodeURIComponent(searchKeyword.value)}`
    const response = await axios.get(searchUrl)
    if (Array.isArray(response.data)) {
      // 处理搜索结果
      products.value = response.data.map(item => ({
        id: item.id,
        product_code: item.product_code,
        title: item.name,
        price: item.price,
        image: item.images && item.images.length > 0 
          ? (item.images[0].url || item.images[0].thumbnail_url)
          : 'https://picsum.photos/300/200?random=' + Math.random(),
        isFavorite: favoriteProducts.value[item.product_code] || false
      }))
    } else {
      products.value = []
      console.error('搜索结果格式错误:', response.data)
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请稍后重试')
    products.value = []
  } finally {
    isLoading.value = false
  }
}

// 查看商品详情，同时记录到最近浏览
const viewProduct = (product) => {
  if (product?.product_code) {
    recentViews.value = addToRecentViews(product, recentViews.value)
    router.push({
      path: `/product/${product.product_code}`,
      params: { product_code: product.product_code }
    })
  } else {
    console.error('商品信息异常:', product)
    ElMessage.error('商品信息异常')
  }
}

// 加载最近浏览
const loadRecentViews = () => {
  try {
    const savedViews = localStorage.getItem('recentViews')
    if (savedViews) {
      recentViews.value = JSON.parse(savedViews)
    }
  } catch (error) {
    console.error('加载最近浏览失败:', error)
  }
}

// 加载远程最近浏览 (如果后端有提供相应接口)
const loadRemoteRecentViews = async () => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  if (!isLoggedIn) return
  
  // 如果后端没有提供recent-views接口，可以注释或移除此功能
  // try {
  //   const response = await axios.get('/api/products/recent-views/')
  //   if (response.data.length > 0) {
  //     recentViews.value = response.data.map(product => ({
  //       id: product.id,
  //       title: product.name,
  //       price: product.price,
  //       image: product.images && product.images.length > 0 
  //         ? product.images[0].thumbnail_url
  //         : 'https://picsum.photos/300/200?random=' + Math.random()
  //     }))
  //     
  //     // 保存到localStorage
  //     localStorage.setItem('recentViews', JSON.stringify(recentViews.value))
  //   }
  // } catch (error) {
  //   console.error('加载远程最近浏览失败:', error)
  // }
}

// 加载轮播图数据 (使用产品图片)
const loadSlides = async () => {
  try {
    // 默认加载第一个分类的商品作为轮播图
    const response = await axios.get(`/api/products/categories/${mainCategories.value[0].id}/products/?limit=3`)
    
    if (response.data.length > 0) {
      slides.value = response.data.map((product, index) => ({
        product_code: product.product_code,
        image: product.images && product.images.length > 0 
          ? product.images[0].url || product.images[0].thumbnail_url || `https://picsum.photos/1200/400?random=${index+1}`
          : `https://picsum.photos/1200/400?random=${index+1}`,
        alt: product.name
      }))
    }
  } catch (error) {
    console.error('加载轮播图失败:', error)
  }
}

// 登录/个人中心跳转
const goToLogin = () => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  if (isLoggedIn) {
    router.push('/Mine')
  } else {
    router.push('/login')
  }
}
let apiUrl = '';
// 生命周期钩子
onMounted(async () => {
  // 1. 加载分类数据
  if (!loadCategoriesFromCache()) {
    console.log('从服务器加载分类数据')
    await fetchCategories()
  }
   if (mainCategories.value.length > 0 && !currentCategory.value) {
    currentCategory.value = mainCategories.value[0].id
    currentSubCategories.value = mainCategories.value[0].children || []
  }

  try {
    if (currentSubCategory.value) {
      apiUrl = `/api/products/categories/${currentSubCategory.value}/products/`;
    } else if (currentCategory.value) {
      apiUrl = `/api/products/categories/${currentCategory.value}/products/`;
    } else if (mainCategories.value.length > 0) {
      apiUrl = `/api/products/categories/${mainCategories.value[0].id}/products/`;
    }

    // 只加载一次商品数据
    products.value = await handleLoadProducts(apiUrl, {
      page: page.value,
      currentSort: currentSort.value,
      searchKeyword: searchKeyword.value,
      favoriteProducts: favoriteProducts.value,
      status: 1
    });
  } catch (error) {
    console.error('加载商品失败:', error);
  }
  
  // 3. 加载最近浏览
  loadRecentViews()
  loadRemoteRecentViews()
  
  // 5. 加载轮播图数据
  await loadSlides()
  
  // 启动轮播
  setInterval(() => {
    currentSlideIndex.value = (currentSlideIndex.value + 1) % slides.value.length
  }, 5000)

  // 监听登录状态变化
  window.addEventListener('login-status-changed', () => {
    loadFavorites() // 重新加载收藏状态
    loadRemoteRecentViews() // 加载远程最近浏览
  })
  
  // 添加滚动监听
  const searchContent = document.querySelector('.search-content')
  if (searchContent) {
    searchContent.addEventListener('scroll', handleScroll)
  }
})

onUnmounted(() => {
  const searchContent = document.querySelector('.search-content')
  if (searchContent) {
    searchContent.removeEventListener('scroll', handleScroll)
  }
})

// 滚动处理函数
const handleScroll = (event) => {
  const element = event.target
  const scrollTop = element.scrollTop
  const scrollHeight = element.scrollHeight
  const clientHeight = element.clientHeight
  
  // 当距离底部50px时就加载新内容
  if (scrollHeight - (scrollTop + clientHeight) <= 50 && !isLoading.value) {
    isLoading.value = true;
    page.value += 1; // 增加页码
    
    // 确保使用正确的API URL
    let currentApiUrl = '';
    if (currentSubCategory.value) {
      currentApiUrl = `/api/products/categories/${currentSubCategory.value}/products/`;
    } else if (currentCategory.value) {
      currentApiUrl = `/api/products/categories/${currentCategory.value}/products/`;
    } else if (mainCategories.value.length > 0) {
      currentApiUrl = `/api/products/categories/${mainCategories.value[0].id}/products/`;
    }
    
    handleLoadProducts(currentApiUrl, {
      page: page.value,
      currentSort: currentSort.value,
      searchKeyword: searchKeyword.value,
      favoriteProducts: favoriteProducts.value
    }).then(result => {
      // 将新加载的商品添加到现有列表
      products.value = [...products.value, ...result]
      isLoading.value = false
    }).catch(error => {
      console.error('加载更多商品失败:', error)
      isLoading.value = false
    })
  }
}

// 监听搜索关键词变化，自动搜索（防抖处理）
// let searchTimeout = null
// watch(searchKeyword, (newValue) => {
//   if (searchTimeout) clearTimeout(searchTimeout)

//   if (newValue.trim()) {
//     searchTimeout = setTimeout(() => {
//       // 只有当输入长度大于1且处于搜索模式时才自动搜索
//       if (newValue.trim().length > 1) {
//       page.value = 1
//       products.value = []
//       viewMode.value = 'search'
//       showSort.value = true
//         handleSearch() // 直接调用搜索函数
//       }
//     }, 500) // 500ms防抖
//   }
// })

// 添加清空搜索函数
const clearSearch = () => {
  searchKeyword.value = ''
  viewMode.value = 'recommend'
  products.value = []
  page.value = 1
  
  // 重新加载推荐商品
  if (currentCategory.value) {
    apiUrl = `/api/products/categories/${currentCategory.value}/products/`;
    handleLoadProducts(apiUrl, {
        page: page.value,
        currentSort: currentSort.value,
      searchKeyword: '',
        favoriteProducts: favoriteProducts.value
    }).then(result => {
      products.value = result;
    });
  }
}

// 跳转到搜索页面
const goToSearchPage = () => {
  if (searchKeyword.value) {
    router.push({
      path: '/search',
      query: { q: searchKeyword.value }
    })
  } else {
    router.push('/search')
  }
}

// 生成模拟商品数据
const generateMockProducts = (count = 5) => {
  const categories = [
    '办公设备', '乐器', '摄像器材', '美妆个护', '健身器材',
    '家用电器', '运动装备', '家具家居', '鞋靴箱包', '服务穿搭',
    '大众书籍', '教材教辅', '数码配件'
  ];
  
  const mockProducts = [];
  
  // 查找当前选择的分类名称
  let currentCategoryName = '';
  if (currentCategory.value) {
    const category = mainCategories.value.find(c => c.id === currentCategory.value);
    if (category) {
      currentCategoryName = category.display_name;
    }
  }
  
  // 如果有子分类，优先使用子分类名称
  if (currentSubCategory.value) {
    const subCategory = currentSubCategories.value.find(c => c.id === currentSubCategory.value);
    if (subCategory) {
      currentCategoryName = subCategory.display_name;
    }
  }
  
  // 如果找不到匹配的分类名称，使用默认的第一个分类
  if (!currentCategoryName || !categories.includes(currentCategoryName)) {
    currentCategoryName = categories[0];
  }
  
  for (let i = 0; i < count; i++) {
    const imageNum = Math.floor(Math.random() * 3) + 1;
    
    // 处理特殊情况：鞋靴箱包的图片名称
    let imagePath;
    if (currentCategoryName === '鞋靴箱包' && imageNum === 3) {
      imagePath = `/img/${currentCategoryName} ${imageNum}.jpg`; // 有空格
    } else {
      imagePath = `/img/${currentCategoryName}${imageNum}.jpg`; // 无空格
    }
    
    mockProducts.push({
      product_code: `mock-${Date.now()}-${i}`,
      title: `${currentCategoryName}样品${i + 1}`,
      name: `${currentCategoryName}样品${i + 1}`,
      price: Math.floor(Math.random() * 1000) + 100,
      image: imagePath,
      isFavorite: false
    });
  }
  
  return mockProducts;
};

// 修改 loadProducts 函数的调用处理
const handleLoadProducts = async (url, params) => {
  try {
    const result = await loadProducts(url, params);
    
    // 获取当前分类ID和URL中的分类ID
    const urlCategoryId = url.match(/\/categories\/(\d+)\/products/);
    const categoryId = urlCategoryId ? urlCategoryId[1] : null;
    
    // 如果是第一页且返回的数据少于5条，添加模拟数据
    if (params.page === 1 && result.length < 5) {
      console.log('数据不足5条，添加模拟数据');
      const mockCount = 5 - result.length;
      const mockProducts = generateMockProducts(mockCount);
      return [...result, ...mockProducts];
    }
    
    // 如果是加载更多（非第一页）但没有返回数据，添加模拟数据
    if (params.page > 1 && result.length === 0) {
      console.log('加载更多没有数据，添加模拟数据');
      return generateMockProducts(5);
    }
    
    return result;
  } catch (error) {
    console.error('加载商品失败:', error);
    // 发生错误时返回模拟数据
    return generateMockProducts(5);
  }
};
</script>

<style scoped>
/* 原有样式保持不变 */
.main-container {
  display: flex;
  height: calc(100vh - 60px);
  overflow: hidden;
  width: 100%;
}

.left-buttons {
  width: 100px;
  background-color: #f5f5f5;
  padding: 10px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow-y: auto; /* 滚动条只在左侧分类栏显示 */
  height: 100%; /* 高度占满父容器 */

}
.left-buttons::-webkit-scrollbar {
  width: 4px;
}
.side-btn {
  width: 100%;
  padding: 12px 0;
  margin: 5px 0;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 14px;
  color: #333;
}

.side-btn.active {
  background-color: #fff;
  color: #45a049;
  font-weight: bold;
}

.search-content {
  flex: 1;
  overflow-y: auto;
  padding: 0 10px;
  width: calc(100% - 100px);
  justify-content: center;
}

.search-container {
  max-width: 1200px;
  width: 100%;
  height: fit-content; 
  margin:auto;
  padding: 10px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.search-form {
  display: flex;
  flex: 1;
}

.search-box {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
}

.search-button {
  padding: 8px 15px;
  background-color: #45a049;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.login-btn {
  margin-left: 10px;
  background: none;
  border: none;
  cursor: pointer;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
}

.category-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.category-btn {
  padding: 6px 12px;
  background-color: #f0f0f0;
  border: none;
  border-radius: 15px;
  cursor: pointer;
  font-size: 13px;
}

.category-btn.active {
  background-color: #45a049;
  color: white;
}

.carousel-container {
  position: relative;
  height: 160px;
  margin-bottom: 15px;
  overflow: hidden;
}

.carousel-slide {
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: opacity 0.5s ease;
}

.carousel-slide.active {
  opacity: 1;
}

.carousel-slide img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.product-card {
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
}

.product-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.product-info {
  padding: 8px;
}

.product-title {
  font-size: 13px;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  color: #f56c6c;
  font-weight: bold;
}

.loading {
  text-align: center;
  padding: 15px;
  color: #888;
}

.no-products {
  text-align: center;
  padding: 30px;
  color: #666;
  font-size: 14px;
}

.bottom-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 1px solid #eee;
  padding: 8px 0;
}

.button-container {
  display: flex;
  justify-content: space-around;
}

/* 添加新样式 */
.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title h2 {
  font-size: 16px;
  margin: 0;
}

.section-toggle {
  background-color: transparent;
  border: 1px solid #45a049;
  color: #45a049;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  cursor: pointer;
}

.sort-container {
  display: flex;
  gap: 8px;
  margin-bottom: 15px;
  overflow-x: auto;
  padding-bottom: 5px;
}

.sort-btn {
  background-color: #f0f0f0;
  border: none;
  padding: 5px 10px;
  border-radius: 12px;
  font-size: 12px;
  cursor: pointer;
  white-space: nowrap;
}

.sort-btn.active {
  background-color: #45a049;
  color: white;
}

.category-count {
  font-size: 10px;
  color: #999;
  margin-left: 3px;
}

.product-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  z-index: 2;
}

/* .favorite-btn {
  background-color: rgba(255, 255, 255, 0.7);
  border: none;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #ccc;
  cursor: pointer;
}

.favorite-btn.active {
  color: #ff6b6b;
} */

.product-card {
  position: relative;
}

.recent-views {
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.recent-views h3 {
  font-size: 14px;
  margin-bottom: 10px;
}

.recent-views-container {
  display: flex;
  overflow-x: auto;
  gap: 10px;
  padding-bottom: 10px;
}

.recent-view-item {
  flex: 0 0 80px;
  text-align: center;
  cursor: pointer;
}

.recent-view-item img {
  width: 70px;
  height: 70px;
  object-fit: cover;
  border-radius: 4px;
}

.recent-view-title {
  font-size: 11px;
  margin-top: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 80px;
}

.left-buttons::-webkit-scrollbar {
  width: 4px;
}

/* 原有样式保持不变 */
.side-btn {
  width: 100%;
  padding: 12px 0;
  margin: 5px 0;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 14px;
  color: #333;
}

.side-btn.active {
  background-color: #fff;
  color: #45a049;
  font-weight: bold;
}

/* ... 其他原有样式保持不变 ... */
</style>